// 请求
import axios from 'axios'
import serverIp from '../../../config/serverIp'
import qs from 'qs'
axios.defaults.baseURL = serverIp.serverArgument + serverIp.serverHost + ':' + serverIp.serverPort
axios.defaults.withCredentials = false // 解决axios post不能传参

const role = {
  state: {
    // 角色列表数据
    roleListSta: [],
    // 新增角色模态框
    roleAddModalSta: false,
    // 编辑角色模态框
    roleEditModalSta: false,
    // 当前选中的角色
    roleOneSta: {},
    // 资源配置模态框
    roleResourceModalSta: false,
    // 角色对应的资源
    roleResourceListSta: []
  },
  mutations: {
    // 角色列表数据
    roleListMut: (state, payload) => {
      state.roleListSta = payload
    },
    // 角色列表数据(添加一条数据)
    roleAddMut: (state, payload) => {
      let role = payload.state
      state.roleListSta.push(role)
    },
    // 角色列表数据(更新一条数据)
    roleListUpdateOneMut: (state, payload) => {
      let role = payload.state
      let roleId = payload.state.id.toString()
      let roleListSta = state.roleListSta
      for (let i of roleListSta) {
        if (i.id == roleId) {
          i.id = role.id
          i.name = role.name
          i.crtime = role.crtime
          i.chtime = role.chtime
          break
        }
      }
    },
    // 角色列表数据(删除一条数据)
    roleListDelOneMut: (state, payload) => {
      let roleId = payload.state.id.toString()
      let roleListSta = state.roleListSta
      for (let i = 0; i < roleListSta.length; i++) {
        if (roleListSta[i].id == roleId) {
          roleListSta.splice(i, 1)
          break
        }
      }
    },
    // 新增角色模态框
    roleAddModalMut: (state, payload) => {
      state.roleAddModalSta = payload.state
    },
    // 资源配置模态框
    roleResourceModalMut: (state, payload) => {
      state.roleResourceModalSta = payload.state
    },
    // 编辑角色模态框
    roleEditModalMut: (state, payload) => {
      state.roleEditModalSta = payload.state
    },
    // 当前选中的角色
    roleOneMut: (state, payload) => {
      state.roleOneSta = payload.state
    },
    // 角色对应的资源
    roleResourceListMut: (state, payload) => {
      state.roleResourceListSta = payload
    }
  },
  actions: {
    // 角色列表数据
    roleListAct: (context) => {
      let obj = qs.stringify({})
      axios.post('/acl_role/list', obj).then(res => {
        let roleList = res.data
        context.commit('roleListMut', roleList)
      })
    },
    // 角色对应的资源
    roleResourceListAct: (context) => {
      // 当前选择的角色id
      let roleId = {}
      roleId.id = context.state.roleOneSta.id
      let obj = qs.stringify(roleId)
      axios.post('/acl_role/roleResource', obj).then(res => {
        let resourceList = res.data
        context.commit('roleResourceListMut', resourceList)
      })
    }
  }
}
export default role
